<template>
	<div>
		<div class="choice-knowledge" :class="{'edit': type==='edit'}">
			<span class="title">关联知识点:</span>
			<span
				class=" f-12 text-overflow-1"
				:class="{
					'knowledge-name': showSearch === false,
				}"
			>{{ knowledgeName }}</span>
			<span class="num f-12">{{ knowledgeNumStr }}</span>
			<el-button v-if="knowledgeList.length" type="text" @click="onLook">查看</el-button>
			<span />
			<el-button
				v-if="type==='add'"
				size="mini"
				class="theme_font_color theme-border-color"
				@click="onChoice"
			>
				选择知识点
			</el-button>
			<el-button
				v-if="type==='edit'"
				type="text"
				size="mini"
				icon="el-icon-edit"
				@click="onChoice"
			>
				重新选择
			</el-button>
			<span v-if="showSearch">&ensp;或&ensp;</span>
			<el-popover
				:width="knowledgePopoverWidth"
				trigger="manual"
				style="flex: 1;"
				ref="popover"
				popper-class="knowledge-popover"
				v-if="showSearch"
			>
				<ul v-if="knowledgeSearchList.length > 0" class="el-select-dropdown__list">
					<li
						@click="handleKnowledgeClick(item)"
						class="el-select-dropdown__item"
						v-for="(item, index) in knowledgeSearchList"
						:key="item.knowledgeId"
						:class="{
							selected: item.isFocus,
							hover: item.isHover
						}"
						:tabIndex="index + 100"
						:title="`【${item.subjectName}】 - ${item.knowledgeTitle}`"
					>
						【{{ item.subjectName }}】- {{ item.knowledgeTitle }}
					</li>
				</ul>
				<p v-else-if="knowledgeSearchList.length <= 0 && !isSearching" class="el-button--text" style="padding: 10px 8px;">当前视频的科目下，找不到符合条件的知识点，请更换关键词重试</p>
				<el-input
					v-model="searchTxt"
					placeholder="输入知识点名，回车，会自动关联"
					maxlength="100"
					show-word-limit
					style="flex: 1;min-width: 400px;"
					slot="reference"
					@keyup.enter.native="handleSearchEnter"
					ref="searchInput"
					class="knowledge-search-input"
					clearable
					:loading="isSearching"
				>
					<img
						slot="suffix"
						src="../../../../../assets/images/enter.png"
						width="17"
						height="17"
						style="vertical-align:middle;"
					>
				</el-input>
			</el-popover>
		</div>
		<!-- 选择知识点弹窗 -->
		<knowledge-dialog
			v-if="knowledgeDialogData.isShowKnowledgeDialog"
			:visibly.sync="knowledgeDialogData.isShowKnowledgeDialog"
			:project-name="knowledgeDialogData.projectName"
			:subject-id="knowledgeDialogData.subjectId"
			:subject-name="knowledgeDialogData.subjectName"
			:is-multiple="knowledgeDialogData.knowledgeMultiple"
			:default-data="knowledgeDialogData.defaultData"
			@submit="onKnowledgeSubmit"
		>
			<template #project>
				<div>
					<div class="project-select">
						<span class="title">项目</span>
						<el-select v-model="knowledgeDialogData.projectId" @change="onChangeProject">
							<el-option
								v-for="project in projectList"
								:key="project.projectId"
								:label="project.projectName"
								:value="project.projectId"
							/>
						</el-select>
					</div>
					<div class="project-select">
						<span class="title">科目</span>
						<el-select placeholder="科目" v-model="knowledgeDialogData.subjectId" @change="onChangeSubject">
							<el-option
								v-for="subject in subjectList"
								:key="subject.subjectId"
								:label="subject.subjectName"
								:value="subject.subjectId"
							/>
						</el-select>
					</div>
				</div>
			</template>
		</knowledge-dialog>
		<!-- 查看删除知识点 -->
		<knowledge-delete-dialog
			v-if="deleteDialogData.isShow"
			delete-confirm
			:visibly.sync="deleteDialogData.isShow"
			v-model="knowledgeList"
			:upper-deal="type==='edit'"
			@delete="handelDelete"
		/>
	</div>
</template>
<script>
	import coursewareApi from "@rc/apis/rc/courseware.mjs";
	import cbnApi from "@rc/apis/cbn/index.mjs";

	import KnowledgeDialog from "@rc/pages/components/knowledge-dialog/index.vue"; //选择知识点
	import KnowledgeDeleteDialog from "@rc/pages/components/knowledge-delete-dialog/index.vue"; //查看删除知识点
	export default {
		name: "choice-knowledge",
		props: {
			projectSubjectList: {
				type: Array,
				default: () => []
			},
			type: {
				type: String,
				default: "add"
			},
			defaultData: {
				type: Array,
				default: () => []
			},
			resourceVideoDotId: {
				type: String,
				default: ""
			},
			showSearch: {
				type: Boolean,
				default: false
			}
		},
		watch: {
			projectSubjectList: {
				handler(res) {
					if (res && res.length) {
						this.projectList = res.map((project) => {
							return {
								projectId: project.projectId,
								projectName: project.projectName
							};
						});
						this.subjectList = res[0].subjectList;
						this.subjectAllList = res.map(({ subjectList }) => subjectList).flat();
					}
				},
				immediate: true
			},
			defaultData: {
				handler(val) {
					if (val) {
						this.knowledgeList = JSON.parse(JSON.stringify(val));
					}
				},
				immediate: true
			}
		},
		components: {
			KnowledgeDialog,
			KnowledgeDeleteDialog
		},
		data() {
			return {
				//弹窗信息
				knowledgeDialogData: {
					isShowKnowledgeDialog: false,
					subjectId: "",
					projectId: "",
					knowledgeMultiple: true
				},
				deleteDialogData: {
					isShow: false
				},
				//选择的知识点内容
				knowledgeList: [],
				//项目列表
				projectList: [],
				//科目列表
				subjectList: [],
				searchTxt: '',
				knowledgeSearchList: [],
				knowledgePopoverWidth: 580,
				subjectAllList: [],
				isSearching: false,
			};
		},
		computed: {
			knowledgeName() {
				//展示的选择知识点名字
				return this.knowledgeList.length ? this.knowledgeList[0].knowledgeName : "--";
			},
			knowledgeNumStr() {
				//展示知识点未展开的数量
				if (this.knowledgeList.length && this.knowledgeList.length !== 1) {
					return `+${this.knowledgeList.length - 1}`;
				}
				return "";
			}
		},
		mounted() {
			window.addEventListener('click', this.handleWindowClick);
			this.getPopoverWidth();
		},
		beforeDestroy() {
			window.removeEventListener('click', this.handleWindowClick);
		},
		methods: {
			onChoice() {
				if (!this.projectList.length) {
					this.$message.warning("没有获取到课件关联项目");
					return;
				}
				this.knowledgeDialogData.projectId = this.projectList[0].projectId;
				this.knowledgeDialogData.projectName = this.projectList[0].projectName;
                //重置科目列表
                this.subjectList = this.projectSubjectList.find((project) => project.projectId === this.knowledgeDialogData.projectId).subjectList;
				this.knowledgeDialogData.subjectId = this.subjectList[0].subjectId;
				this.knowledgeDialogData.subjectName = this.subjectList[0].subjectName;
				this.knowledgeDialogData.defaultData = this.knowledgeList;
				this.knowledgeDialogData.isShowKnowledgeDialog = true;
			},
			//点击查看
			onLook() {
				this.deleteDialogData.isShow = true;
			},
			//修改项目
			onChangeProject(projectId) {
				this.knowledgeDialogData.projectName = this.projectList.find((project) => project.projectId === projectId).projectName;
				this.subjectList = this.projectSubjectList.find((project) => project.projectId === projectId).subjectList;
				this.knowledgeDialogData.subjectId = this.subjectList[0].subjectId;
				this.knowledgeDialogData.subjectName = this.subjectList[0].subjectName;
			},
			//修改项目
			onChangeSubject(subjectId) {
				this.knowledgeDialogData.subjectName = this.subjectList.find((subject) => subject.subjectId === subjectId).subjectName;
			},
			//删除
			handelDelete(arr) {
				const resultArr = this.knowledgeList.filter((i1) => {
					return !arr.some((i2) => i2.knowledgeId === i1.knowledgeId);
				});
				const knowledgeIdList = resultArr.map((knowledge) => knowledge.knowledgeId);
				const dotDescription = this.getDescription(resultArr);
				coursewareApi.updateResourceVideoKnowledge({
					data: {
						resourceVideoDotId: this.resourceVideoDotId,
						knowledgeList: knowledgeIdList,
						dotDescription
					},
					success: () => {
						//刷新视频
						this.$emit("update-success");
						this.$message.success("知识点删除成功");
						this.deleteDialogData.isShow = false;
					}
				});
			},
			/**
			 * 更新关联的知识点
			 */
			updateResourceVideoKnowledge(knowledgeList) {
				this.$confirm("确定更新关联知识点吗？", "提示", {
					type: "warning"
				}).then(() => {
					const dotDescription = this.getDescription(knowledgeList);
					const knowledgeIdList = knowledgeList.map((knowledge) => knowledge.knowledgeId);
					coursewareApi.updateResourceVideoKnowledge({
						data: {
							resourceVideoDotId: this.resourceVideoDotId,
							knowledgeList: knowledgeIdList,
							dotDescription
						},
						success: () => {
							//刷新视频
							this.$emit("update-success");
							this.$message.success("更新知识点成功");
							this.knowledgeDialogData.isShowKnowledgeDialog = false;
						}
					});
				});
			},
			// 拼接描述信息
			getDescription(knowledgeList) {
				let dotDescription = knowledgeList.length ? knowledgeList[0].knowledgeName : "";
				const dotDescriptionNum = knowledgeList.length && knowledgeList.length !== 1 ? "+" + (knowledgeList.length - 1) : "";
				if (this.knowledgeList.length) {
					dotDescription = dotDescription.length > 10 ? dotDescription + "..." : dotDescription;
					dotDescription = dotDescription.length ? "知识点：" + dotDescription : dotDescription;
				}
				return dotDescription + dotDescriptionNum;
			},
			onKnowledgeSubmit(knowledgeList) {
				if (!knowledgeList.length) {
					this.$message.warning("请选择知识点");
					return;
				}
				if (knowledgeList.length > 20) {
					this.$message.warning("最多可以关联20个知识点");
					return;
				}
				if (this.type === "add") {
					//新建
					this.knowledgeList = knowledgeList;
					this.knowledgeDialogData.isShowKnowledgeDialog = false;
					return;
				}
				if (this.type === "edit") {
					//已打点重新选择知识点
					this.updateResourceVideoKnowledge(knowledgeList);
				}
			},
			/**
			 * 返回打点显示的知识点名字10个阶段...+X
			 * 返回选择的知识点列表
			 */
			api_getKnowledgeList() {
				let knowledgeName = "";
				if (this.knowledgeList.length) {
					knowledgeName = this.knowledgeName.length > 10 ? this.knowledgeName + "..." : this.knowledgeName;
					knowledgeName = knowledgeName.length ? "知识点：" + knowledgeName : knowledgeName;
				}
				return {
					dotDescription: knowledgeName + this.knowledgeNumStr,
					knowledgeList: this.knowledgeList,
					knowledgeIdList: this.knowledgeList.map((knowledge) => knowledge.knowledgeId)
				};
			},
			handleSearchEnter() {
				this.isSearching = true;
				cbnApi.queryKnowledgeListByName({
					knowledgeTitle: this.searchTxt,
					subjectIdList: this.subjectAllList.map(({ subjectId }) => subjectId),
				}).then((res) => {
					res.forEach((item, index) => {
						item.knowledgeName = item.knowledgeTitle;
						item.isFocus = index === 0;
						item.isHover = index === 0;
					});
					this.knowledgeSearchList.splice(0, this.knowledgeSearchList.length, ...res);
					this.$nextTick(() => {
						const dmp = document.querySelector('.knowledge-popover:nth-of-type(n+2)');
						if (dmp.isAddClickListener !== true) {
							dmp.isAddClickListener = true;
							dmp.addEventListener('keyup', (e) => {
								switch(e.keyCode) {
									case 40:
										{
											const it = this.knowledgeSearchList.find(({ isFocus }) => isFocus);
											const idx = this.knowledgeSearchList.findIndex(({ isFocus }) => isFocus);
											it && (it.isFocus = false);
											if (idx < this.knowledgeSearchList.length - 1) {
												this.knowledgeSearchList[idx + 1].isFocus = true;
											} else if (this.knowledgeSearchList.length) {
												this.knowledgeSearchList[0].isFocus = true;
											}
										}
										break;
									case 38:
										{
											const it = this.knowledgeSearchList.find(({ isFocus }) => isFocus);
											const idx = this.knowledgeSearchList.findIndex(({ isFocus }) => isFocus);
											it && (it.isFocus = false);
											if (idx > 0) {
												this.knowledgeSearchList[idx - 1].isFocus = true;
											} else if (this.knowledgeSearchList.length) {
												this.knowledgeSearchList[this.knowledgeSearchList.length - 1].isFocus = true;
											}
										}
										break;
									case 13:// enter
										{
											if (this.knowledgeSearchList.length <= 0) {
												return;
											}
											this.$refs.popover.doClose();
											const it = this.knowledgeSearchList.find(({ isFocus }) => isFocus);
											if (it && this.knowledgeList.some(({ knowledgeId }) => knowledgeId === it.knowledgeId) === false) {
												this.knowledgeList.push(it);
												this.$nextTick(this.getPopoverWidth);		
											}
											this.searchTxt = '';
											this.$refs.searchInput.focus();		
										}
										break;
								}
							});
						}
						this.$refs.searchInput.blur();
						dmp.focus();
					});
					this.$refs.popover.doShow();
				}).finally(() => {
					this.isSearching = false;
				});
			},
			handleKnowledgeClick(item) {
				this.$refs.popover.doClose();
				this.searchTxt = '';
				if (this.knowledgeList.some(({ knowledgeId }) => knowledgeId === item.knowledgeId) === false) {
					this.knowledgeList.push(item);
				}
				this.$nextTick(this.getPopoverWidth);
				this.$refs.searchInput.focus();	
			},
			handleWindowClick() {
				this.$refs.popover.doClose();
			},
			getPopoverWidth() {
				const dm = document.querySelector('.knowledge-search-input');
				const style = getComputedStyle(dm);
				this.knowledgePopoverWidth = parseFloat(style.width);
			},
		}
	};
</script>
<style lang="less" scoped>
	.choice-knowledge {
		display: flex;
		// height: 50px;
		line-height: 50px;
		align-items: center;
		flex-wrap: wrap;
		&.edit {
			height: 40px;
			line-height: 40px;
		}
		.title {
			font-weight: bold;
			font-size: 14px;
			flex-shrink: 0;
			margin-right: 5px;
		}
		.f-12 {
			font-size: 12px;
		}
		.num {
			flex-shrink: 0;
		}
		.el-button {
			height: 32px !important;
			margin-left: 10px;
			&.edit {
				padding: 7px 8px;
			}
		}
	}
	.left-chapter /deep/ {
		.project-select {
			display: flex;
			align-items: center;
			margin-bottom: 10px !important;
		}
		.title {
			margin-right: 5px;
		}
	}
	.knowledge-search-input /deep/ .el-input__inner {
		padding-right: 100px;
	}
	.knowledge-name {
		flex: 1;
	}
</style>

<style lang="less">
	.knowledge-popover {
		padding: 0;
	}
</style>
